package radiostation;

import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import javax.persistence.EntityManager;
import javax.swing.JOptionPane;
import model.Artist;
import model.MusicGroup;
import radiostation.common.ArtistRepository;

public class ArtistUI extends BaseJFrame {

    private Artist selectedArtist;
    private final EntityManager entityManager;
    private final MainUI parent;

    public ArtistUI(EntityManager entityManager, MainUI mainUI) {
        this.entityManager = entityManager;
        this.parent = mainUI;

        initComponents();

        // open in the center of the window
        setLocationRelativeTo(null);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        bindingGroup = new org.jdesktop.beansbinding.BindingGroup();

        artistQuery = java.beans.Beans.isDesignTime() ? null : entityManager.createQuery("SELECT a FROM Artist a");
        artistList = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : org.jdesktop.observablecollections.ObservableCollections.observableList(artistQuery.getResultList());
        jScrollPane1 = new javax.swing.JScrollPane();
        artistTable = new javax.swing.JTable();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jButton3 = new javax.swing.JButton();
        jButton4 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setResizable(false);

        artistTable.setName("artistTable"); // NOI18N
        artistTable.getTableHeader().setReorderingAllowed(false);

        org.jdesktop.swingbinding.JTableBinding jTableBinding = org.jdesktop.swingbinding.SwingBindings.createJTableBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, artistList, artistTable);
        org.jdesktop.swingbinding.JTableBinding.ColumnBinding columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${artistId}"));
        columnBinding.setColumnName("Artist Id");
        columnBinding.setColumnClass(Integer.class);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${artisticName}"));
        columnBinding.setColumnName("Artistic Name");
        columnBinding.setColumnClass(String.class);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${birthday}"));
        columnBinding.setColumnName("Birthday");
        columnBinding.setColumnClass(java.util.Date.class);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${birthplace}"));
        columnBinding.setColumnName("Birthplace");
        columnBinding.setColumnClass(String.class);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${firstName}"));
        columnBinding.setColumnName("First Name");
        columnBinding.setColumnClass(String.class);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${lastName}"));
        columnBinding.setColumnName("Last Name");
        columnBinding.setColumnClass(String.class);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${sex}"));
        columnBinding.setColumnName("Sex");
        columnBinding.setColumnClass(String.class);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${musicGenre.name}"));
        columnBinding.setColumnName("Music Genre");
        columnBinding.setColumnClass(String.class);
        bindingGroup.addBinding(jTableBinding);
        jTableBinding.bind();
        jScrollPane1.setViewportView(artistTable);
        artistTable.getAccessibleContext().setAccessibleName("artistTable");
        artistTable.getAccessibleContext().setAccessibleDescription("");

        jButton1.setForeground(java.awt.Color.blue);
        jButton1.setText("Νέο");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                createNewArtist(evt);
            }
        });

        jButton2.setForeground(java.awt.Color.red);
        jButton2.setText("Διαγραφή");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                deleteSelectedArtist(evt);
            }
        });

        jButton3.setText("Επεξεργασία");
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                editSelectedArtist(evt);
            }
        });

        jButton4.setText("Έξοδος");
        jButton4.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                exitForm(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 788, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jButton1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButton3)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jButton2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jButton4)
                        .addContainerGap())))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 506, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jButton1)
                            .addComponent(jButton3)
                            .addComponent(jButton2))
                        .addContainerGap(36, Short.MAX_VALUE))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jButton4)
                        .addContainerGap())))
        );

        bindingGroup.bind();

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void createNewArtist(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_createNewArtist

        selectedArtist = new Artist();

        try {

            ArtistEditUI artistEditUI = new ArtistEditUI(entityManager);
            artistEditUI.setVisible(true);
            setEnabled(false);

            artistEditUI.addWindowListener(new WindowListener() {
                public void windowClosed(WindowEvent arg0) {
                    if (((MyWindowEvent) arg0).exitAndSave) {

                        if (!entityManager.getTransaction().isActive()) {
                            entityManager.getTransaction().begin();
                        }

                        Artist selectedArtist1 = artistEditUI.getSelectedArtist();
                        // Τον γράφω στην ΒΔ
                        entityManager.persist(selectedArtist1);
                        entityManager.flush();

                        // add the artist in the list
                        artistList.add(artistEditUI.getSelectedArtist());
                        // Επέλεξέ τον στον πίνακα
                        int row = artistList.size() - 1;
                        artistTable.setRowSelectionInterval(row, row);
                        artistTable.scrollRectToVisible(artistTable.getCellRect(row, 0, true));

                        // commit transaction
                        entityManager.getTransaction().commit();

                    }
                    // Ενεργοποίησε και πάλι την τρέχουσα φόρμα
                    setEnabled(true);
                }

                public void windowActivated(WindowEvent arg0) {
                }

                public void windowClosing(WindowEvent arg0) {
                }

                public void windowDeactivated(WindowEvent arg0) {
                }

                public void windowDeiconified(WindowEvent arg0) {
                }

                public void windowIconified(WindowEvent arg0) {
                }

                public void windowOpened(WindowEvent arg0) {
                }
            });

        } catch (Exception e) {
            Exception eχ = e;
            throw e;
        }

    }//GEN-LAST:event_createNewArtist

    private void deleteSelectedArtist(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_deleteSelectedArtist

        // Έλεγχος αν έχει επιλεγεί καλλιτέχνης
        int row = artistTable.getSelectedRow();

        if (row == -1) {
            showWarningMessage("Δεν έχει επιλεχθεί καλλιτέχνης");
            return;
        }

        // Επιβεβαίωση διαγραφής
        int choice = showPrompt("Επιβεβαίωση διαγραφής καλλιτέχνη", "Διαγραφή του καλλιτέχνη");
        if (choice != 0) {
            return;
        }

        // Ανάκτηση του καλλιτέχνη προς διαγραφή
        Artist artistToRemove = artistList.get(row);

        // Διαγραφή του καλλιτέχνη από την ΒΔ
        // Δημιουργία μίας νέας δοσοληψίας
        if (!entityManager.getTransaction().isActive()) {
            entityManager.getTransaction().begin();
        }

        // Διαγραφή του καλλιτέχνη από τα συγκροτήματα στα οποία ανήκει
        for (MusicGroup mg : artistToRemove.getMusicGroupList()) {
            mg.getArtistList().remove(artistToRemove);
        }

        // remove artist from db
        entityManager.remove(artistToRemove);

        // remove artist from list that used for binding
        artistList.remove(artistToRemove);

        // commit transation
        entityManager.getTransaction().commit();


    }//GEN-LAST:event_deleteSelectedArtist

    private void editSelectedArtist(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_editSelectedArtist
        // Έλεγχος αν έχει επιλεγεί καλλιτέχνης
        int row = artistTable.getSelectedRow();

        if (row == -1) {
            // Αναδυόμενο παράθυρο
            JOptionPane.showMessageDialog(this, "Δεν έχει επιλεχθεί καλλιτέχνης", "Σφάλμα",
                    JOptionPane.WARNING_MESSAGE);
            return;
        }

        selectedArtist = artistList.get(row);

        try {
            ArtistEditUI artistEditUI = new ArtistEditUI(selectedArtist, entityManager);
            artistEditUI.setVisible(true);
            setEnabled(false);

            artistEditUI.addWindowListener(new WindowListener() {
                public void windowClosed(WindowEvent arg0) {

                    if (((MyWindowEvent) arg0).exitAndSave) {
                        Artist editedArtist = artistEditUI.getSelectedArtist();

                        try {
                            if (!entityManager.getTransaction().isActive()) {
                                entityManager.getTransaction().begin();
                            }
                            ArtistRepository artistRepository = new ArtistRepository(entityManager);
                            Artist stateArtist = artistRepository.findById(selectedArtist.getArtistId());

                            stateArtist.setFirstName(editedArtist.getFirstName());
                            stateArtist.setLastName(editedArtist.getLastName());
                            stateArtist.setArtisticName(editedArtist.getArtisticName());
                            stateArtist.setBirthday(editedArtist.getBirthday());
                            stateArtist.setBirthplace(editedArtist.getBirthplace());
                            stateArtist.setMusicGenre(editedArtist.getMusicGenre());
                            stateArtist.setSex(editedArtist.getSex());

                            //replace current table row with the new one
                            artistList.set(row, stateArtist);

                            //artistTable.setRowSelectionInterval(row, row);
                            //artistTable.scrollRectToVisible(artistTable.getCellRect(row, 0, true));
                            // commit transaction
                            entityManager.getTransaction().commit();
                        } catch (Exception e) {
                            entityManager.getTransaction().rollback();
                        }
                    }
                    // enable the current form
                    setEnabled(true);
                }

                public void windowActivated(WindowEvent arg0) {
                }

                public void windowClosing(WindowEvent arg0) {
                }

                public void windowDeactivated(WindowEvent arg0) {
                }

                public void windowDeiconified(WindowEvent arg0) {
                }

                public void windowIconified(WindowEvent arg0) {
                }

                public void windowOpened(WindowEvent arg0) {
                }
            });

        } catch (Exception e) {
            Exception eχ = e;
            throw e;
        }
    }//GEN-LAST:event_editSelectedArtist

    private void exitForm(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_exitForm

        // enable parent form
        parent.setEnabled(true);
        // close current form and destroy all the attached resources
        dispose();
    }//GEN-LAST:event_exitForm

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private java.util.List<model.Artist> artistList;
    private javax.persistence.Query artistQuery;
    private javax.swing.JTable artistTable;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JButton jButton4;
    private javax.swing.JScrollPane jScrollPane1;
    private org.jdesktop.beansbinding.BindingGroup bindingGroup;
    // End of variables declaration//GEN-END:variables
}
